<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import {updatePost} from '@/api/posts.js'
const route = useRoute();
const router = useRouter();

const postId = route.params.id;
const loading = ref(false);

const form = reactive({
  title: '',
  content: '',
  status: 1
});
// 获取原始文章
const fetchPost = async () => {
  loading.value = true;
  try {
    const res = await axios.get(`/api/posts/${postId}`);
    form.title = res.data.title;
    form.content = res.data.content;
    form.status = res.data.status;
  } catch (error) {
    ElMessage.error('加载文章失败');
  } finally {
    loading.value = false;
  }
};

// 保存修改
const savePost = async () => {

  if(!form.title.trim() || !form.content.trim()){
    ElMessage.warning('标题和内容不能为空');
    return;
  }
  try {
    await updatePost(postId,form)
    ElMessage.success('文章更新成功');
    await router.push(`/post/${postId}`);
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

const goBack = () => {
  router.back();
};

onMounted(() => {
  fetchPost();
});
</script>

<template>
  <div style="max-width: 720px; margin: 40px auto;">
    <el-button @click="goBack" style="margin-bottom: 20px;">返回</el-button>

    <el-card v-if="!loading" shadow="hover">
      <el-form label-position="top">
        <el-form-item label="文章标题">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="文章内容">
          <el-input
              type="textarea"
              v-model="form.content"
              placeholder="请输入内容"
              :rows="12"
              resize="vertical"
          />
        </el-form-item>
        <el-select v-model="form.status" placeholder="请选择状态" style="margin-bottom: 10px">
          <el-option label="发布" :value="1"></el-option>
          <el-option label="草稿" :value="0"></el-option>
        </el-select>
        <el-form-item>
          <el-button type="primary" @click="savePost">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div v-else style="text-align: center; margin-top: 100px;">
      正在加载文章内容...
    </div>
  </div>
</template>

<style scoped>
</style>
